package com.wildwolf.project.wildwolf.service;

import android.os.AsyncTask;
import android.os.RemoteException;
import android.util.Log;

import com.wildwolf.project.wildwolf.service.aidl.IXmppConnection;
import com.wildwolf.project.wildwolf.service.aidl.IXmppFacade;
import com.wildwolf.project.wildwolf.utils.LogTagUtil;

/**
 * 连接到Xmpp服务器 异步登录
 * 
 * @author LEON
 * 
 */
public class LoginAsyncTask extends AsyncTask<IXmppFacade, Integer, Boolean> {

	/**
	 * 正在连接.
	 */
	public static final int STATE_CONNECTION_RUNNING = 0;
	/**
	 * 连接成功，正在认证
	 */
	public static final int STATE_LOGIN_RUNNING = 1;
	/**
	 * 认证成功
	 */
	public static final int STATE_LOGIN_SUCCESS = 2;
	/**
	 * 认证失败
	 */
	public static final int STATE_LOGIN_FAILED = 3;

	private static final String TAG = LogTagUtil.getLogTag(LoginAsyncTask.class);
	/**
	 * 连接对象
	 */
	private IXmppConnection mConnection;
	/**
	 * 错误信息
	 */
	private String mErrorMessage;

	/**
	 * Constructor.
	 */
	public LoginAsyncTask() {
	}

	@Override
	protected Boolean doInBackground(IXmppFacade... params) {
		boolean result = true;
		IXmppFacade facade = params[0];
		try {
			publishProgress(STATE_CONNECTION_RUNNING);
			mConnection = facade.createConnection();
			if (!mConnection.connect()) {
				mErrorMessage = mConnection.getErrorMessage();
				return false;
			}
			publishProgress(STATE_LOGIN_RUNNING);

			if (!mConnection.login()) {
				mErrorMessage = mConnection.getErrorMessage();
				publishProgress(STATE_LOGIN_FAILED);
				return false;
			}
			publishProgress(STATE_LOGIN_SUCCESS);
		} catch (RemoteException e) {
			mErrorMessage = "Exception during connection :" + e;
			result = false;
		}
		return result;
	}

	/**
	 * 取消操作
	 */
	@Override
	protected void onCancelled() {
		try {
			if (mConnection != null && mConnection.isAuthentificated()) {
				mConnection.disconnect();
			}
		} catch (RemoteException e) {
			Log.d(TAG, "Remote exception", e);
		}
	}

	/**
	 * 获取错误信息
	 * 
	 * @return 如果返回NULL 则表示没有错误信息
	 */
	public String getErrorMessage() {
		return mErrorMessage;
	}
}
